<?php
/**
 * 用户推广类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 18/12/20
 * Time: 下午16:30
 */
namespace app\common\model;

use think\Db;

class UserHierarchy extends Catalog
{
    private const TABLE_NAME = 'user_hierarchy';
    private const TABLE_USER = 'user';

    public function __construct()
    {
        parent::__construct(self::TABLE_NAME);
    }

    /**
     * 添加层级数据
     * @author 王海东
     * @date
     * @param string $hierarchy_id 推广者组id
     * @return int  返回自增id
     * @throws \Exception
     */
    public function addHierarchy(string $hierarchy_id = '')
    : int {

        $res = $this->add('', $hierarchy_id);

        return $res;
    }

    /**
     * 查询推广的客户
     * @author 王海东
     * @date
     * @param int $user_id 用户id
     * @return array
     * @throws \Exception
     */
    public function getChild(int $user_id)
    : array {
        $u    = new User();
        $info = $u->info($user_id);

        $hierarchy_id = $info['hierarchy_id'];

        $pcInfo = $this->getNodeInfo($hierarchy_id);

        if (!$pcInfo) {
            return [];
        }

        //所有子节点
        try {
            $posterity = Db::name(self::TABLE_NAME)
                           ->alias('h')
                           ->field([
                               "h.id",
                               "h.pid",
                               "u.name",
                               "u.tel",
                           ])
                           ->where("h.ln", ">", $pcInfo["ln"])
                           ->where("h.rn", "<", $pcInfo["rn"])
                           ->join(self::TABLE_USER.' u', 'h.id = u.hierarchy_id', 'left')
                           ->select();
        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }

        if (!$posterity) {
            return [];
        }

        $list = $this->find_level($posterity, $hierarchy_id);

        return $list;
    }

    /**
     * 获取用户层级
     * @author 王海东
     * @date
     * @param array $list  数据
     * @param int   $id    上级id
     * @param int   $level 等级
     * @return array
     */
    private function find_level(array $list, int $id = 1, int $level = 1)
    : array {
        $lists = [];

        foreach ($list as $val) {
            $lists[$val['id']] = $val;
        }

        static $arr = [];

        foreach ($lists as $key => $val) {
            if ($val['pid'] == $id) {
                $val['level'] = $level;
                $arr[]        = $val;
                unset($lists[$key]);
                $this->find_level($lists, $val['id'], $level + 1);
            }
        }

        return $arr;
    }
}